package com.bzqn.baseframe;

import java.io.File;
import java.io.IOException;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.google.gson.Gson;

@SuppressLint("HandlerLeak")
public class BZQNLaunchActivity extends AbstructBaseActivity {
	public static final String LOCAL_CONFIG_KEY_APPVERSION = "appversion";
	private int delayTime;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(showWellcomeActivity()){
				startActivity(initWelcomeActivity());
			} else {
				startActivity(initLaunchActivity());
			}
			finish();
		};
	};
	private boolean showWellcomeActivity(){
		PackageManager packageManager = getPackageManager();  
        // getPackageName()是你当前类的包名，0代表是获取版本信息  
        try {
			PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
			float appVersion = Float.parseFloat(packInfo.versionName);
			if(appVersion > getFloatValueForKey(LOCAL_CONFIG_KEY_APPVERSION)){
				setFloatForKey(LOCAL_CONFIG_KEY_APPVERSION, appVersion);
				return true;
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		} 
		return false;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (initContentViewResId() != 0) {
			setContentView(initContentViewResId());
		} else {
			setContentView(initContentImageView());
		}
		onDownloadConfigSuccess("");
		// 下载config文件
//		new FinalHttp().get(getConfigUrl(),
//				new AjaxCallBack<String>() {
//					@Override
//					public void onSuccess(String t) {
//						super.onSuccess(t);
//						onDownloadConfigSuccess(t);
//					}
//
//					@Override
//					public void onFailure(Throwable t, int errorNo,
//							String strMsg) {
//						super.onFailure(t, errorNo, strMsg);
//						try {
//							String json = Utils.convertStreamToString(getAssets().open(BZQNFrameActivity.CONFIG_FILENAME));
//							if(json.endsWith("/n")){
//								json = new StringBuffer(json).delete(json.lastIndexOf("/n"), json.length()).toString();
//							} 
//							onDownloadConfigSuccess(json);
//						} catch (Exception e) {
//							e.printStackTrace();
//						}
//					}
//
//					@Override
//					public void onStart() {
//						super.onStart();
//					}
//				});
	}

	@Override
	void onHttpRet(String content) {

	}

	protected String getConfigUrl() {
//		return "http://114.215.196.175/config.json";
		return "";
	}
	private void onDownloadConfigSuccess(String t) {
		if (TextUtils.isEmpty(t)) {
			laucnhTimer();
			return;
		}
		Config config = new Gson().fromJson(t, Config.class);
		delayTime = config.getDelayTime();
		File local = new File(getCacheDir(), BZQNFrameActivity.CONFIG_FILENAME);
		File localImage = new File(getCacheDir(), "splash.png");
		if (config.isClearCache()) {
			// 删除缓存中的文件
			if (local.exists()) {
				local.delete();
			}
		} else {
			// 覆盖文件
			try {
				Utils.saveFile(local, t);
			} catch (IOException e) {
				Log.i("FILE", "保存失败");
				e.printStackTrace();
			}
		}

		if (config.isNewLaunchImage()) {
			// 需要新图片，下载
			if (!TextUtils.isEmpty(config.getSplashImageUrl())) {
				Log.i("IMAGE", "加载在线图片");
				new FinalHttp().download(config.getSplashImageUrl(),
						localImage.getAbsolutePath(), new AjaxCallBack<File>() {
							@Override
							public void onSuccess(File t) {
								setContentImageView(t);
								laucnhTimer();
								super.onSuccess(t);
							}

							@Override
							public void onFailure(Throwable t, int errorNo,
									String strMsg) {
								super.onFailure(t, errorNo, strMsg);
								laucnhTimer();
							}
						});
			} else {
				laucnhTimer();
			}
		} else {
			// 如果不需要新图片
			if (localImage.exists()) {
				setContentImageView(localImage);
				laucnhTimer();
			} else {
				laucnhTimer();
			}
		}
	}

	protected Intent initLaunchActivity() {

		return new Intent(this, NavicationActivity.class);
	}
	protected Intent initWelcomeActivity() {
		return new Intent(this, BZQNWelcomeActivity.class);
	}

	protected int launchDelayTime() {

		return delayTime;
	}

	protected int initContentViewResId() {

		return 0;
	}

	protected ImageView initContentImageView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(Color.RED);
		return i;
	}

	protected void laucnhTimer() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				SystemClock.sleep(launchDelayTime());
				mHandler.sendEmptyMessage(0);
			}
		}).start();
	}

	private void setContentImageView(File file) {
		Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath());
		ImageView launcherImage = new ImageView(BZQNLaunchActivity.this);
		launcherImage.setImageBitmap(b);
		setContentView(launcherImage);

	}
}
